package com.imti.httpdemo;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import org.json.JSONException;

public class MainActivity extends AppCompatActivity
{

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }

    private void initView()
    {
        Button btnSendGet = findViewById(R.id.btn_send_get);
        Button btnSendPost = findViewById(R.id.btn_send_post);

        btnSendGet.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                sendGet();
            }
        });

        btnSendPost.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                sendPost();
            }
        });
    }

    private void sendPost()
    {
        new Thread()
        {
            @Override
            public void run()
            {
                super.run();

                try
                {
                    //1.创建访问的URL
                    URL url = new URL(
                        "http://apis.juhe.cn/simpleWeather/cityList");

                    //2.打开链接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setConnectTimeout(10 * 1000);
                    connection.setReadTimeout(10 * 1000);

                    //POST请求必须设置请求类型，请求类型默认为GET
                    connection.setRequestMethod("POST");

                    //POST请求不支持缓存
                    connection.setUseCaches(false);

                    //开启参数流
                    connection.setDoOutput(true);

                    //key=8149094547f3e900f1ea47e6a25de938
//                    String param = "key=8149094547f3e900f1ea47e6a25de938";
                    String param =
                        "key=" + URLEncoder.encode("8cf90bdd00d8ff3b42af97f57977b8ba", "UTF-8");

                    OutputStream os = connection.getOutputStream();
                    os.write(param.getBytes());
                    //输出流写入完毕后刷新
                    os.flush();
                    //获取接口返回结果
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)
                    {
                        String result = readInputStream(connection.getInputStream());

//                        Log.d(TAG, "POST请求结果：" + result);
                        ////JsonUtil.parseCityList(result);
                        CityModel[] cityList = JsonUtil.parseCityListByGson(result);

                        for (CityModel model : cityList)
                        {
                            Log.d(TAG,
                                "id = " + model.getId() +
                                    " province = " + model.getProvince() +
                                    " city = " + model.getCity() +
                                    " district = " + model.getDistrict());
                        }

                    }

                } catch (IOException e)
                {
                    e.printStackTrace();
                }

            }
        }.start();
    }

    private void sendGet()
    {
        new Thread()
        {
            @Override
            public void run()
            {
                super.run();

                try
                {
                    //1.创建访问的URL
                    URL url = new URL(
                        "http://apis.juhe.cn/simpleWeather/cityList?key=8149094547f3e900f1ea47e6a25de938");

                    //2.打开连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    //3.设置参数
                    //设置连接超时时长
                    connection.setConnectTimeout(10 * 1000);
                    //设置返回超时时长
                    connection.setReadTimeout(10 * 1000);
                    //设置访问类型，默认为GET类型
                    connection.setRequestMethod("GET");

                    //判断网络请求是否成功
                    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK)
                    {
                        //4.获取返回数据
                        InputStream is = connection.getInputStream();
                        String result = readInputStream(is);

                        Log.d(TAG, "请求结果：" + result);
                    }

                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private String readInputStream(InputStream is) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        StringBuffer sb = new StringBuffer();
        String str = "";

        while (null != (str = br.readLine()))
        {
            sb.append(str);
        }

        return sb.toString();
    }
}